<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="user-info">
        <el-avatar :size="40" :src="consultantInfo.avatar" />
        <span class="name">{{ consultantInfo.name }}</span>
      </div>
      <el-button type="danger" @click="exitConsultation">
        退出咨询
      </el-button>
    </div>
    
    <div class="messages-area" ref="messagesArea">
      <div v-for="message in messages" 
           :key="message.id" 
           :class="['message', message.senderId === userInfo.id ? 'message-right' : 'message-left']">
        <el-avatar 
          :size="30" 
          :src="message.senderId === userInfo.id ? userInfo.avatar : consultantInfo.avatar" 
        />
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.createdAt) }}</div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入消息..."
        @keyup.enter.native.exact="sendMessage"
      />
      <el-button type="primary" @click="sendMessage" :loading="sending">
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import WebSocketClient from '@/utils/websocket'
import Cookies from 'js-cookie'

const route = useRoute()
const router = useRouter()
const consultationId = ref(route.params.consultationId)
const messages = ref([])
const inputMessage = ref('')
const sending = ref(false)
const messagesArea = ref(null)
const wsClient = new WebSocketClient()

const consultantInfo = ref({
  id: route.query.consultantId,
  name: route.query.consultantName,
  avatar: route.query.consultantAvatar || '/default-avatar.png'
})

const userInfo = ref(JSON.parse(Cookies.get('userInfo') || '{}'))

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesArea.value) {
    setTimeout(() => {
      messagesArea.value.scrollTop = messagesArea.value.scrollHeight
    }, 100)
  }
}

// 获取历史消息
const fetchHistoryMessages = async () => {
  try {
    const res = await request.get(`/admin/consultation/${consultationId.value}/messages`)
    if (res.data && Array.isArray(res.data.records)) {
      messages.value = res.data.records.map(msg => ({
        id: msg.id || Date.now(),
        content: msg.content,
        senderId: msg.senderId,
        createdAt: msg.createdAt || new Date().toISOString()
      }))
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取历史消息失败:', error)
    ElMessage.error('获取历史消息失败')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || sending.value) return
  
  sending.value = true
  const messageContent = inputMessage.value.trim()
  
  try {
    // 使用HTTP请求发送消息
    const res = await request.post('/admin/consultation/message/send', {
      consultationId: consultationId.value,
      content: messageContent,
      senderId: userInfo.value.id,
      receiverId: consultantInfo.value.id,
      userId: userInfo.value.id
    })
    
    if (res.code === 200) {
      // 清空输入框
      inputMessage.value = ''
      
      // 立即将消息添加到本地列表
      messages.value.push({
        id: Date.now(),
        content: messageContent,
        senderId: userInfo.value.id,
        createdAt: new Date().toISOString()
      })
      scrollToBottom()
    } else {
      ElMessage.error(res.msg || '发送消息失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 处理接收到的消息
const handleMessage = (message) => {
  console.log('前台收到WebSocket消息:', message)
  // 直接将接收到的消息添加到列表中
  messages.value.push({
    id: message.id || Date.now(),
    content: message.content,
    senderId: message.senderId,
    createdAt: message.createdAt || new Date().toISOString()
  })
  scrollToBottom()
}

// 建立WebSocket连接
const connectWebSocket = () => {
  try {
    wsClient.connect(`/ws/consultation/${consultationId.value}/${userInfo.value.id}`)
    wsClient.addMessageHandler(handleMessage)
    console.log('WebSocket连接已建立')
  } catch (error) {
    console.error('WebSocket连接失败:', error)
    ElMessage.error('消息接收服务连接失败，请刷新页面重试')
  }
}

// 退出咨询
const exitConsultation = async () => {
  try {
    await ElMessageBox.confirm('确定要退出当前咨询吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    // 断开WebSocket连接
    wsClient.disconnect()
    
    // 返回上一页
    router.back()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出咨询失败:', error)
      ElMessage.error('退出咨询失败')
    }
  }
}

onMounted(async () => {
  if (!consultationId.value || !consultantInfo.value.id) {
    ElMessage.error('无效的咨询会话')
    return
  }
  
  try {
    // 先获取历史消息
    await fetchHistoryMessages()
    
    // 然后建立WebSocket连接
    connectWebSocket()
  } catch (error) {
    console.error('初始化聊天失败:', error)
    ElMessage.error('初始化聊天失败，请刷新页面重试')
  }
})

onBeforeUnmount(() => {
  // 清理WebSocket连接
  wsClient.disconnect()
})
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 100px);
  width: 800px; /* 固定宽度 */
  margin: 20px auto;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  border-radius: 8px 8px 0 0;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.name {
  font-size: 16px;
  font-weight: 500;
}

.messages-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  min-height: 0;
  background-color: #f5f5f5;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 10px;
}

.message-right {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #fff;
  word-break: break-all;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message-right .message-text {
  background-color: #95ec69;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.input-area {
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #eee;
  border-radius: 0 0 8px 8px;
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.input-area .el-textarea {
  flex: 1;
}

.input-area .el-button {
  align-self: flex-end;
  height: 40px; /* 调整按钮高度 */
}
</style> 